// pages/index/nearbyTeams/shenqingqianyue/shenqingqianyue.js
import request from '../../../../utils/request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userid:'',
    doctorInfo:{},
    servicePac:[],
    jigou:{},
    team:{},
    selectedPackage:{},
    userInfo: {
      name: '王强',
      gender: '1',
      age: '28',
      idCard: '371456198908090543',
      phone: '15678909900',
      address: '怀柔区洛西县建设路青连小区6-601'
    },
    startDate: '',
    signInfo: {
      institutionName: '洛西社区卫生服务站',
      teamName: '李明明团队',
      doctorName: '李明明',
      packageName: '老人服务包',
      period: '1年',
      startDate: '2020-09-01',
      fee: '120'
    },
    remark: '',
    showCalendar: false,
    minDate: new Date().getTime(),
    showPackagePopup: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 如果有传入的参数，更新签约信息
    if (options.id) {
      this.getSignInfo(options.id);
      this.getTeamDetail(options.id);
      this.getServicePac();
    }
    this.getServicePackages(); // 获取服务包列表
  },
  getServicePac() {
    request({
      url: 'package/package/list',
      method: "GET",
      success: (result) => {
        console.log(result.data.rows);
        this.setData({
          servicePac: result.data.rows
        });

      },
      fail: (err) => {
        console.error('获取服务包失败', err);
        wx.showToast({
          title: '获取服务包失败',
          icon: 'none'
        });
      }
    });
  },
  getSignInfo(id) {
    request({
      url: `system/doctor/${id}`,
      method: 'GET',
      success: (res) => {
        console.log(res.data.data)
        if (res.data.code === 200) {
          this.setData({
            doctorInfo: res.data.data
          });
        }
      }
    });
    // 获取签约相关信息
  },

  onSwitchUser() {
    wx.navigateTo({
      url: '/pages/user/familyMembers/familyMembers'
    });
  },

  onSelectInstitution() {
    wx.navigateTo({
      url: '/pages/index/nearbyInstitutions/nearbyInstitutions'
    });
  },

  onSelectTeam() {
    wx.navigateTo({
      url: '/pages/index/nearbyTeams/nearbyTeams'
    });
  },

  onSelectDoctor() {
    wx.navigateTo({
      url: '/pages/index/nearbyTeams/doctorList/doctorList'
    });
  },
  getTeamDetail(id) {
    request({
      url: 'system/team/'+id,
      method: 'GET',
      success: (result) => {
        this.setData({
          team:result.data.data
        })
        request({
          url: 'system/institution/'+result.data.data.institutionid,
          method: 'GET',
          success: (res) => {
            this.setData({
              jigou:res.data.data
            })
          },
          fail: (err) => {},
          complete: (res) => {},
        })
      },
      fail: (err) => {},
      complete: (res) => {},
    })
  },
  onSelectPackage() {
    wx.navigateTo({
      url: '/pages/index/servicePackages/servicePackages'
    });
  },

  onSelectDate() {
    this.setData({
      showCalendar: true
    });
  },

  onCloseCalendar() {
    this.setData({
      showCalendar: false
    });
  },

  onSelectStartDate(event) {
    const date = new Date(event.detail);
    const startDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    this.setData({
      startDate: startDate,
      showCalendar: false
    });
  },

  onSubmit() {
    // 表单验证
    if (!this.validateForm()) {
      return;
    }

    // 提交签约申请
    wx.showModal({
      title: '提示',
      content: '确认提交签约申请？',
      success: (res) => {
        if (res.confirm) {
          this.submitApplication();
          wx.navigateTo({
            url: '/pages/index/nearbyTeams/result/result',
          })
        }
      }
    });
  },

  validateForm() {
    // 验证必填字段
    const { signInfo } = this.data;
    if (!signInfo.institutionName || !signInfo.teamName || !signInfo.doctorName || !signInfo.packageName) {
      wx.showToast({
        title: '请完善签约信息',
        icon: 'none'
      });
      return false;
    }
    return true;
  },

  submitApplication() {
    const data = {
      userId: this.data.userInfo.id,
      institutionId: this.data.signInfo.institutionId,
      teamId: this.data.signInfo.teamId,
      doctorId: this.data.signInfo.doctorId,
      packageId: this.data.signInfo.packageId,
      startDate: this.data.signInfo.startDate,
      remark: this.data.remark
    };

    wx.showLoading({
      title: '提交中...'
    });
    let userId=wx.getStorageSync('userid')
    console.log(userId);
    const dateObject = new Date(this.data.startDate);
    // 调用签约接口
    request({
      url: 'contractlog/contractlog',
      method: 'POST',
      data: {
        userId:userId,
        status:1,
        organization:this.data.jigou.id,
        doctor:this.data.doctorInfo.id,
        team:this.data.team.id,
        servicePackage:this.data.selectedPackage.packageId,
        remark:this.data.remark,
        cycle:this.data.selectedPackage.contractCycle,
        effectiveDate:dateObject,
        effectiveStatus:0,
        type:0
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 2000);
            }
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '提交失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 获取服务包列表
  getServicePackages() {
    request({
      url: 'package/package/list',
      method: 'GET',
      data: {
        institutionid: this.data.signInfo.institutionId
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            servicePac: res.data.rows
          });
        }
      }
    });
  },

  // 显示服务包选择器
  showPackagePopup() {
    this.setData({
      showPackagePopup: true
    });
  },

  // 关闭服务包选择器
  onClosePackage() {
    this.setData({
      showPackagePopup: false
    });
  },

  // 确认选择服务包
  onConfirmPackage(event) {
    const selectedPackage = event.detail.value;
    this.setData({
      'signInfo.packageName': selectedPackage.packageName,
      'signInfo.packageId': selectedPackage.id,
      'signInfo.fee': selectedPackage.price,
      showPackagePopup: false,
      selectedPackage:selectedPackage
    });
  },
})